import 'whatwg-fetch';

// 插入header头中plat信息
const defaultOption = {
    // headers: {
    //     plat: 'h5'
    // },
    mode: 'cors',
    redirect: 'follow',
    credentials: 'same-origin',
    async: true
};
export const AliasOfFetch = function (url, option = {}) {
    var cacheControl = {};
    if ((option.method === 'POST' || option.method === 'post') && (typeof option.body) === 'string') {
        if (option.headers && !option.headers['content-type']) {
            option.headers = {
                ...option.headers,
                'content-type': 'application/x-www-form-urlencoded;charset=UTF-8'
            };
        } else {
            option.headers = { 'content-type': 'application/x-www-form-urlencoded;charset=UTF-8' };
        }
    }
    url += (url.indexOf('?') === -1 ? '?' : '&') + 't=' + new Date().valueOf();
    const headers = { ...defaultOption.headers, ...cacheControl.headers, ...option.headers };
    const options = { ...defaultOption, ...cacheControl, ...option, headers }
    return fetch(url, options);
};

// 处理x-www-form-urlencoded
export const parseFormUrlencoded = (data) => {
    if (window.URLSearchParams) {
        let form = new URLSearchParams();
        for (let key in data) {
            if (data[key] === undefined) {
                continue
            }
            form.append(key, data[key]);
        }
        return form;
    } else {
        let res = [];
        for (let key in data) {
            if (data[key] === undefined) {
                continue
            }
            res.push(`${encodeURIComponent(key)}=${encodeURIComponent(data[key])}`);
        }
        return res.join('&');
    }
}

export const bannerFetch = () => {
    return AliasOfFetch('/api/v5/index/banners')
        .then(res => res.json());
}

// 预约列表
export const getAppointmentList = (options) => {
    return AliasOfFetch(``, {
        method: 'POST',
        body: parseFormUrlencoded(options)
    })
        .then(res => res.json());
}
